const db = require("../config/db");

/**
 * 获取所有广告
 */
exports.getAll = async () => {
  const [rows] = await db.query("SELECT * FROM ads ORDER BY id DESC");
  return rows;
};

/**
 * 根据 ID 获取广告
 */
exports.getById = async (id) => {
  const [rows] = await db.query("SELECT * FROM ads WHERE id=?", [id]);
  return rows[0];
};

/**
 * 新增广告
 */
exports.add = async (ad) => {
  const { type, position, title, image, link, status } = ad;
  const [result] = await db.query(
    "INSERT INTO ads (type, position, title, image, link, status, created_at) VALUES (?, ?, ?, ?, ?, ?, NOW())",
    [type, position, title, image, link, status]
  );
  return { id: result.insertId, ...ad, createdAt: new Date().toISOString() };
};

/**
 * 更新广告
 */
exports.update = async (id, ad) => {
  const { type, position, title, image, link, status } = ad;
  await db.query(
    "UPDATE ads SET type=?, position=?, title=?, image=?, link=?, status=? WHERE id=?",
    [type, position, title, image, link, status, id]
  );
  return { id: Number(id), ...ad };
};

/**
 * 删除广告
 */
exports.remove = async (id) => {
  await db.query("DELETE FROM ads WHERE id=?", [id]);
};
